<template>
  <div class="list-container">
    <van-pull-refresh
      v-model="isRefreshLoading"
      :success-text="refreshSuccessText"
      @refresh="onRefresh"
      success-duration="1500"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <!-- <van-cell
          v-for="(item, index) in list"
          :key="index"
          :title="item.title" -->
        <articleItem 
        v-for="(item, index) in list" 
        :key="index"
        :article='item'
         />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from "@/api/atricle";
import articleItem from "@/components/article-item";
export default {
  components: {
    articleItem,
  },
  name: "Articlelist",
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [], // 文章列表数据
      loading: false, // 上拉加载更多的 loading 状态
      finished: false, // 是否加载结束
      error: false, // 是否加载失败
      timestamp: null, // 请求下一页数据的时间戳
      isRefreshLoading: false,
      refreshSuccessText: "刷新成功",
    };
  },
  methods: {
    async onRefresh() {
      try {
        // 获取请求数据
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1,
        });
        // 模拟失败的情况
        //  if(Math.random()>0.5){
        //    JSON.parse('addsgjhj')
        //  }
        // 请求数据成功以后，在数组前面添加数据
        this.list.unshift(...data.data.results);
        // 3. 关闭下拉刷新的 loading 状态
        this.isRefreshLoading = false;
        const { results } = data.data;
        this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`;
      } catch (err) {
        this.isRefreshLoading = false; // 关闭下拉刷新的 loading 状态
        this.$toast("刷新失败");
      }
    },
    async onLoad() {
      try {
        // 获取请求数据
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1,
        });
        // if(Math.random()>0.5){
        //   JSON.parse('addsgjhj')
        // }
        const { results } = data.data;
        this.list.push(...results);
        this.loading = false;
        if (results.length) {
          // 更新获取下一页数据的时间戳
          this.timestamp = data.data.pre_timestamp;
        } else {
          // 没有数据了，设置加载状态结束，不再触发上拉加载更多了
          this.finished = true;
        }
      } catch (err) {
        // console.log("获取失败", err);
        this.error = true;
        this.loading = false;
      }
    },
  },
};
</script>
<style lang="less" scoped>
.list-container {
  position: fixed;
  top: 180px;
  bottom: 100px;
  right: 0;
  left: 0;
  overflow-y: auto;
}
</style>